﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using KPIS.GERP.GBMS.APP_UI.Common;
using KPIS.GERP.GBMS.BLL;
using KPIS.GERP.GBMS.IBLL;
using KPIS.GERP.GBMS.MODEL;
using Telerik.Web.UI;

namespace KPIS.GERP.GBMS.APP_UI.Form
{
    public partial class BGM_Strategy_KPI : System.Web.UI.Page
    {
        private StrategyKpiBLL straKpiBLL = new StrategyKpiBLL();
        private SystemTypeYearBLL sysTypeYearBLL = new SystemTypeYearBLL();
        private ComboBLL comboBLL = new ComboBLL();
        private CommandControl cmdFac = new CommandControl();
        private IStrategyPlanBLL bal = new StrategyPlanBLL();
        private bool isbind;
        private SsMng ssMng = new SsMng();
        private Main main = new Main();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string seq = Request.QueryString["seq"];
                lblYear.Text = Request.QueryString["year"];
                //string[] strUrl = Request.RawUrl.Split('=');
                //lblStrategy.Text = strUrl[strUrl.Length-1].Replace("%20", " ");
                //bgm_strat_data_map_seq
                DataRow dr = bal.GetStrategyBySequence(int.Parse(seq)).Rows[0];
                lblStrat_map_seq.Text = dr["bgm_strat_list_seq"].ToString();
                lblStrategy.Text = dr["bgm_strat_list_name"].ToString();
                loadKpiType();
                LoadData();
            }
            
        }

        private void LoadData()
        {
            {
                DataRow dr = sysTypeYearBLL.GetDataSystemTypeYear().Rows[0];
                lblMonthType.Text = dr["month"].ToString();
            }

            {
                // If error, please insert
                //  INSERT INTO bgm_mas_year_type (bgm_year_type_name, day_start, month_start)
                //  VALUES ('ไตรมาสงบประมาณ', NULL, 4);
                foreach (DataRow dr in sysTypeYearBLL.GetDataSystemTypeYear().Rows)
                {
                    if (dr["type"] as string == "ไตรมาสงบประมาณ")
                        lblQuarterType.Text = dr["month"].ToString();
                }
                if (String.IsNullOrEmpty(lblQuarterType.Text))
                {
                    throw new Exception("การตั้งค่าระบบ bgm_mas_year_type ยังไม่มีไตรมาสเริ่มต้น กรุณาใส่ข้อมูลลงไตรมาสงบประมาณลงในเทเบิ้ล");
                }
            }

            DataTable dt = straKpiBLL.Search("", "", lblStrat_map_seq.Text, lblYear.Text);
            Grid.DataSource = dt;
            Grid.DataBind();
        }

        private void loadKpiType()
        {
            DataTable info = comboBLL.ListKpiType();
            ddlKpiType_t9.DataSource = info;
            ddlKpiType_t9.DataBind();
        }

        private void OnInsert(object sender, EventArgs e)
        {
            txtMTEF1_t9.Text = txtMTEF1_t9.Text != "" ? txtMTEF1_t9.Text : "0";
            txtMTEF2_t9.Text = txtMTEF2_t9.Text != "" ? txtMTEF2_t9.Text : "0";
            txtMTEF3_t9.Text = txtMTEF3_t9.Text != "" ? txtMTEF3_t9.Text : "0";
            try
            {
                string m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12;
                GetMonthUi(out m1,out m2,out m3,out m4,out m5,out m6,
                              out m7,out m8,out m9,out m10,out m11,out m12);
                straKpiBLL.InsertStrategyKPI(
                    txtName_t9.Text, txtDescr_t9.Text, txtUnit_t9.Text, txtWeight_t9.Text, "", ddlKpiType_t9.SelectedValue, txtScore1_t9.Text, txtScore2_t9.Text, txtScore3_t9.Text, txtScore4_t9.Text, txtScore5_t9.Text, ddlTarket_t9.SelectedValue
                    , m1,m2,m3,m4,m5,m6,m7,m8,m9,m10,m11,m12
                    , txtMTEF1_t9.Text, txtMTEF2_t9.Text, txtMTEF3_t9.Text, lblStrat_map_seq.Text, lblYear.Text, ssMng.EmpSeq);
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('บันทึกเสร็จเรียบร้อย');", true);
            }
            catch
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('เกิดข้อผิดพลาดในการบันทึก');", true);
            }
            LoadData();
            RefreshGrid();
        }

        private void OnUpdate(object sender, EventArgs e)
        {
            txtMTEF1_t9.Text = txtMTEF1_t9.Text != "" ? txtMTEF1_t9.Text : "0";
            txtMTEF2_t9.Text = txtMTEF2_t9.Text != "" ? txtMTEF2_t9.Text : "0";
            txtMTEF3_t9.Text = txtMTEF3_t9.Text != "" ? txtMTEF3_t9.Text : "0";
            try
            {
                string m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12;
                GetMonthUi(out m1, out m2, out m3, out m4, out m5, out m6,
                              out m7, out m8, out m9, out m10, out m11, out m12);
                straKpiBLL.UpdateStrategyKPI(
                    hdSeq.Text, txtName_t9.Text, txtDescr_t9.Text, txtUnit_t9.Text, txtWeight_t9.Text, ddlKpiType_t9.SelectedValue, txtScore1_t9.Text, txtScore2_t9.Text, txtScore3_t9.Text, txtScore4_t9.Text, txtScore5_t9.Text, ddlTarket_t9.SelectedValue
                    , m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12
                    , txtMTEF1_t9.Text, txtMTEF2_t9.Text, txtMTEF3_t9.Text, ssMng.EmpSeq);
                //this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('บันทึกเสร็จเรียบร้อย');", true);
                //RadManager1.Alert("บันทึกเสร็จเรียบร้อย");
            }
            catch
            {
                //this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Message", "alert('เกิดข้อผิดพลาดในการบันทึก');", true);
                //RadManager1.Alert("เกิดข้อผิดพลาดในการบันทึก");
            }
            LoadData();
            MapControl();
        }

        private void OnDelete(object sender, EventArgs e)
        {
            int nRowSelected = 0;
            if (panelGrid.Visible)
            {
                foreach (GridDataItem data in Grid.MasterTableView.GetSelectedItems())
                {
                    straKpiBLL.DeleteStrategyKPI(data.OwnerTableView.DataKeyValues[data.ItemIndex]["Sequence"].ToString());
                    nRowSelected++;
                }
            }
            else
            {
                straKpiBLL.DeleteStrategyKPI(hdSeq.Text);
            }
            LoadData();
            RefreshGrid();
        }

        protected void Grid_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "TargetClick")
            {
                //IList<StrategyDataInfo> stratList = straKpiBLL.Search(Convert.ToInt32(((Label)e.Item.FindControl("targetSequence")).Text), "", "", "", 0);

                hdSeq.Text = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Sequence"].ToString();
                DataRow dr = straKpiBLL.Search(hdSeq.Text, "", lblStrat_map_seq.Text, lblYear.Text).Rows[0];
                txtName_t9.Text = dr["bgm_strat_kpi_name"].ToString();
                txtDescr_t9.Text = dr["bgm_strat_kpi_descr"].ToString();
                txtUnit_t9.Text = dr["unit"].ToString();
                txtWeight_t9.Text = dr["bgm_strat_kpi_weight"].ToString();
                txtScore1_t9.Text = main.MakeZero(dr["score_1"]);
                txtScore2_t9.Text = main.MakeZero(dr["score_2"]);
                txtScore3_t9.Text = main.MakeZero(dr["score_3"]);
                txtScore4_t9.Text = main.MakeZero(dr["score_4"]);
                txtScore5_t9.Text = main.MakeZero(dr["score_5"]);
                ddlKpiType_t9.SelectedValue = dr["bgm_kpi_type_seq"].ToString();
                SetMonthDataRow(dr);
                txtMTEF1_t9.Text = dr["mtef_1"].ToString();
                txtMTEF2_t9.Text = dr["mtef_2"].ToString();
                txtMTEF3_t9.Text = dr["mtef_3"].ToString();
                ddlTarket_t9.SelectedValue = dr["target_type"].ToString();
                MapControl();
                SetPanelKpiVisible();
                //cmdFac.SetPanelCommand(panelCommand, "Edit");
            }            
            else if (e.CommandName == RadGrid.ExpandCollapseCommandName)
            {
                string key_grid1 = (e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Sequence"].ToString();
                DataTable dt = straKpiBLL.Search(key_grid1, "", lblStrat_map_seq.Text, lblYear.Text);

                RadGrid grdIn_t9 = (RadGrid)((GridDataItem)e.Item).ChildItem.FindControl("GridIn_t9");
                grdIn_t9.DataSource = dt;
                grdIn_t9.DataBind();
                return;
            }
            else
            {
                LoadData();
                RefreshGrid();
            }
        }




        protected void Grid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (!isbind)
            {
                RadGrid grid = (RadGrid) sender;
                var ds = GetHeaderText();
                foreach (GridColumn c in grid.MasterTableView.Columns)
                {
                    var uiMap = ds.FirstOrDefault(o => o.HeaderKey == c.UniqueName);
                    if (uiMap != null)
                    {
                        c.HeaderText = uiMap.Value;
                        ((Literal) panelList.FindControl(uiMap.LabelKey)).Text = String.Format("{0}:", uiMap.Value);
                    }
                }
                isbind = true;
            }
        }

        //#####################  Command Control In page  --- Event
        protected void ShowGrid_Click(object sender, EventArgs e)
        {
            //cmdFac.GridCommand(panelList, panelGrid, panelCommand);
            cmdFac.SetPanelCommand(panelCommand, "Grid");
            panelGrid.Visible = true;
            panelList.Visible = false;
        }

        protected void AddNew_Click(object sender, EventArgs e)
        {
            //cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);
            cmdFac.SetPanelCommand(panelCommand, "AddNew");
            panelGrid.Visible = false;
            panelList.Visible = true;
            AddNew.Visible = false;
            //cmdFac.AddNewCommand(panelList, panelGrid, panelCommand);
        }

        protected void Edit_Click(object sender, EventArgs e)
        {
            cmdFac.EditCommand(panelList, panelGrid, panelCommand);
        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            cmdFac.CancelCommand(panelList, panelGrid, panelCommand);
        }

        protected void Save_AddNew_Click(object sender, EventArgs e)
        {
            OnInsertCommand(e);
        }

        protected void Save_Edit_Click(object sender, EventArgs e)
        {
            OnUpdateCommand(e);
            cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
        }

        protected void Delete_Click(object sender, EventArgs e)
        {
            OnDeleteCommand(e);
        }

        public void MapControl()
        {
            cmdFac.ViewCommand(panelList, panelGrid, panelCommand);
        }

        public void RefreshGrid()
        {
            cmdFac.GridCommand(panelList, panelGrid, panelCommand);
        }

        protected void OnInsertCommand(EventArgs e)
        {
            OnInsert(null, null);
        }

        protected void OnUpdateCommand(EventArgs e)
        {
            OnUpdate(null, null);
        }

        protected void OnDeleteCommand(EventArgs e)
        {
            OnDelete(null, null);
        }

        protected void ddlTarket_t9_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            switch (e.Value)
            {
                case "2": // เป้าหมายรวมรายเดือน
                    panelKpiMonthly.Visible = true;
                    panelKpiQuarterly.Visible = false;
                    panelKpiYearly.Visible = false;
                    break;
                case "1": // เป้าหมายรวมรายไตรมาส
                    panelKpiMonthly.Visible = false;
                    panelKpiQuarterly.Visible = true;
                    panelKpiYearly.Visible = false;
                    break;
                case "0": // เป้าหมายรวมรายปี
                    panelKpiMonthly.Visible = false;
                    panelKpiQuarterly.Visible = false;
                    panelKpiYearly.Visible = true;
                    break;
                default: 
                    break;
            }
        }

        #region MiscMethod
        private List<UiMap> GetHeaderText()
        {
            List<UiMap> result = new List<UiMap>();

            int monType = int.Parse(lblMonthType.Text) - 1;

            for (int i = 0; i < StrMonth.Length; i++, monType++)
            {
                if (monType >= StrMonth.Length)
                    monType = 0;
                result.Add(new UiMap { HeaderKey = "target_m" + (i + 1), Value = StrMonth[monType], LabelKey = "lblMonth" + (i + 1) });
            }

            int quarType = int.Parse(lblQuarterType.Text) - 1;

            for (int i = 0; i < StrQuarter.Length; i++, quarType++)
            {
                if (quarType >= StrQuarter.Length)
                    quarType = 0;
                result.Add(new UiMap { HeaderKey = "target_q" + (i + 1), Value = StrQuarter[quarType], LabelKey = "lblQuarter" + (i + 1) });
            }

            result.Add(new UiMap { HeaderKey = "target_year", Value = StrYear, LabelKey = "lblYearCaption" });

            return result;
        }

        private void SetMonthDataRow(DataRow dr)
        {
            txtTragetM1_t9.Text = main.MakeZero(dr["target_m1"]);
            txtTragetM2_t9.Text = main.MakeZero(dr["target_m2"]);
            txtTragetM3_t9.Text = main.MakeZero(dr["target_m3"]);
            txtTragetM4_t9.Text = main.MakeZero(dr["target_m4"]);
            txtTragetM5_t9.Text = main.MakeZero(dr["target_m5"]);
            txtTragetM6_t9.Text = main.MakeZero(dr["target_m6"]);
            txtTragetM7_t9.Text = main.MakeZero(dr["target_m7"]);
            txtTragetM8_t9.Text = main.MakeZero(dr["target_m8"]);
            txtTragetM9_t9.Text = main.MakeZero(dr["target_m9"]);
            txtTragetM10_t9.Text = main.MakeZero(dr["target_m10"]);
            txtTragetM11_t9.Text = main.MakeZero(dr["target_m11"]);
            txtTragetM12_t9.Text = main.MakeZero(dr["target_m12"]);

            txtTargetQ1.Text = main.MakeZero(dr["target_q1"]);
            txtTargetQ2.Text = main.MakeZero(dr["target_q2"]);
            txtTargetQ3.Text = main.MakeZero(dr["target_q3"]);
            txtTargetQ4.Text = main.MakeZero(dr["target_q4"]);

            txtTargetYear.Text = main.MakeZero(dr["target_year"]);
        }

        private void GetMonthUi(out string m1, out string m2, out string m3, out string m4, out string m5, out string m6
            , out string m7, out string m8, out string m9, out string m10, out string m11, out string m12)
        {
            m1 = null; m2 = null; m3 = null; m4 = null; m5 = null; m6 = null; 
            m7 = null; m8 = null; m9 = null; m10 = null; m11 = null; m12 = null;
            switch (ddlTarket_t9.SelectedValue)
            {
                case "2": // เป้าหมายรวมรายเดือน
                    m1 = main.MakeZero(txtTragetM1_t9.Text);
                    m2 = main.MakeZero(txtTragetM2_t9.Text);
                    m3 = main.MakeZero(txtTragetM3_t9.Text);
                    m4 = main.MakeZero(txtTragetM4_t9.Text);
                    m5 = main.MakeZero(txtTragetM5_t9.Text);
                    m6 = main.MakeZero(txtTragetM6_t9.Text);
                    m7 = main.MakeZero(txtTragetM7_t9.Text);
                    m8 = main.MakeZero(txtTragetM8_t9.Text);
                    m9 = main.MakeZero(txtTragetM9_t9.Text);
                    m10 = main.MakeZero(txtTragetM10_t9.Text);
                    m11 = main.MakeZero(txtTragetM11_t9.Text);
                    m12 = main.MakeZero(txtTragetM12_t9.Text);
                    break;
                case "1": // เป้าหมายรวมรายไตรมาส
                    m1 = "0";
                    m2 = "0";
                    m3 = main.MakeZero(txtTargetQ1.Text);
                    m4 = "0";
                    m5 = "0";
                    m6 = main.MakeZero(txtTargetQ2.Text);
                    m7 = "0";
                    m8 = "0";
                    m9 = main.MakeZero(txtTargetQ3.Text);
                    m10 = "0";
                    m11 = "0";
                    m12 = main.MakeZero(txtTargetQ4.Text);
                    break;
                case "0": // เป้าหมายรวมรายปี
                    m1 = "0";
                    m2 = "0";
                    m3 = "0";
                    m4 = "0";
                    m5 = "0";
                    m6 = "0";
                    m7 = "0";
                    m8 = "0";
                    m9 = "0";
                    m10 = "0";
                    m11 = "0";
                    m12 = main.MakeZero(txtTargetYear.Text);
                    break;
            }
        }

        private void SetPanelKpiVisible()
        {
            switch (ddlTarket_t9.SelectedValue)
            {
                case "2": // เป้าหมายรวมรายเดือน
                    panelKpiMonthly.Visible = true;
                    panelKpiQuarterly.Visible = false;
                    panelKpiYearly.Visible = false;
                    break;
                case "1": // เป้าหมายรวมรายไตรมาส
                    panelKpiMonthly.Visible = false;
                    panelKpiQuarterly.Visible = true;
                    panelKpiYearly.Visible = false;
                    break;
                case "0": // เป้าหมายรวมรายปี
                    panelKpiMonthly.Visible = false;
                    panelKpiQuarterly.Visible = false;
                    panelKpiYearly.Visible = true;
                    break;
            }
        }
         
        #endregion

        #region Properties

        private class UiMap
        {
            public string HeaderKey { get; set; }
            public string LabelKey { get; set; }
            public string Value { get; set; }
        }

        private string[] StrMonth
        {
            get { return (GetLocalResourceObject("MonthString") as string).Split(',').ToArray(); }
        }

        private string[] StrQuarter
        {
            get { return (GetLocalResourceObject("QuarterString") as string).Split(',').ToArray(); }
        }

        private string StrYear
        {
            get { return (GetLocalResourceObject("YearlyString") as string); }
        }

        #endregion

        #region Unused

        //string[] strMon = { "ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.", "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค." };
        //string[] strMonth = { "มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม" };
        //string[] strQuarter = { "ไตรมาส ๑", "ไตรมาส ๒", "ไตรมาส ๓", "ไตรมาส ๔" };
        
        //string errorStr = String.Empty;
        //private int ind = 0, indx = 0;
        //private int r = 0;
        //protected void Grid_ItemDataBound2(object sender, GridItemEventArgs e)
        //{
        //    var header = e.Item as GridHeaderItem;
        //    int rT = r++;
        //    errorStr += "Round : " + rT;
        //    errorStr += "running : header" + (header == null ? " is null " : " is not null") + "," + e.Item.UniqueID
        //        + "\n";
        //    if (header != null)
        //    {
        //        int monType = int.Parse(lblMonthType.Text);
        //        int quarType = int.Parse(lblQuarterType.Text);

        //        for (int i = 0; i < StrMonth.Length; i++)
        //        {
        //            int tmpMonth = (i + monType) > StrMonth.Length ? (i + monType) - StrMonth.Length : (i + monType);
        //            int index = tmpMonth - 1;
        //            int indT = ind++;
        //            string indexHeader = "target_m" + (index + 1);
        //            string indexLabel = "lblMonth" + (index + 1);
        //            try
        //            {
        //                header[indexHeader].Text = StrMonth[index] + indT;
        //                errorStr += "iHMt=" + indexHeader + ", id=" + index + ", idT=" + indT
        //                    + " {A=" + header[indexHeader].Text
        //                    + ", B=" + StrMonth[index] + "}" + "\n";
        //            }
        //            catch (Exception ex)
        //            {
        //                errorStr += "iHMe=" + indexHeader + ", id=" + index + ", id=" + indT + "\n";
        //            }

        //            Literal lbl = (Literal)panelList.FindControl(indexLabel);
        //            lbl.Text = String.Format("{0}:", StrMonth[index]);
        //        }
        //        for (int i = 0; i < StrQuarter.Length; i++)
        //        {
        //            int tmpQuarter = (i + quarType) > StrQuarter.Length ? (i + quarType) - StrQuarter.Length : (i + quarType);
        //            int index = tmpQuarter - 1;
        //            int indT = ind++;
        //            string indexHeader = "target_q" + (index + 1);
        //            string indexLabel = "lblQuarter" + (index + 1);
        //            try
        //            {
        //                header[indexHeader].Text = StrMonth[index] + indT;
        //                errorStr += "iHMt=" + indexHeader + ", id=" + index + ", idT=" + indT
        //                    + " {A=" + header[indexHeader].Text
        //                    + ", B=" + StrMonth[index] + "}" + "\n";
        //            }
        //            catch (Exception ex)
        //            {
        //                errorStr += "iHMe=" + indexHeader + ", id=" + index + ", id=" + indT + "\n";
        //            }
        //            Literal lbl = (Literal)panelList.FindControl(indexLabel);
        //            lbl.Text = String.Format("{0}:", StrQuarter[index]);
        //        }
        //    }

        //override protected void OnInit(EventArgs e)
        //{
        //    //
        //    // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //    //
        //    InitializeComponent();
        //    base.OnInit(e);
        //}

        ///// <summary>
        ///// Required method for Designer support - do not modify
        ///// the contents of this method with the code editor.
        ///// </summary>
        //private void InitializeComponent()
        //{
        //    CmdCtrl.Inserted += new EventHandler(OnInsert);
        //    CmdCtrl.Updated += new EventHandler(OnUpdate);
        //    CmdCtrl.Deleted += new EventHandler(OnDelete);
        //}
        #endregion
         
    }
}
